package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mapper.HotelMapper;
import com.ruoyi.mapper.HouseMapper;
import com.ruoyi.mapper.RPMapper;
import com.ruoyi.service.GroundService;
import com.ruoyi.service.HouseService;
import com.ruoyi.service.LogService;
import com.ruoyi.utils.ElongUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    HotelMapper hotelMapper;

    @Autowired
    HouseMapper houseMapper;

    @Autowired
    RPMapper rpMapper;

    @Autowired
    GroundService groundService;

    @Autowired
    LogService logService;

    private static Logger hotelSuccess = LoggerFactory.getLogger("hotel_success");

    @Override
    public JSONObject getElongHouseList(String hotelId) {
        Map hotelObj = hotelMapper.getHotelObjByHotelId(hotelId);
        String eHotelId = hotelObj.get("eHotelId").toString();
        String hotelInfo = ElongUtils.getHotelInfo(eHotelId);
        JSONObject jsonObject = JSONObject.parseObject(hotelInfo);
        JSONArray jsonArray = jsonObject.getJSONObject("Result").getJSONArray("Rooms");
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonArray.getJSONObject(i).put("RPList", new JSONArray());
        }
        return jsonObject.getJSONObject("Result");
    }

    @Override
    @Transactional
    public AjaxResult postAddElongHouse(Map map) {
        String hotelId = map.get("hotelId").toString();
        JSONArray jsonArray = JSONArray.parseArray(map.get("data").toString());

        // 先循环验证房型是否重复
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String eHouseId = jsonObject.getString("RoomID");
            // 这里要验证产品
            JSONArray rpList = jsonObject.getJSONArray("RPList");
            for (int j = 0; j < rpList.size(); j++) {
                String rpName = rpList.getString(j);
                int houseCount = houseMapper.getHouseByEhouseId(eHouseId, hotelId, rpName);
                if (houseCount > 0) {
                    return AjaxResult.error(jsonObject.getString("RoomName") + "<" + rpName + ">已导入！");
                }
            }
        }

        // 添加房型及产品数据
        int addSum = 0;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Integer houseId;
            // 这里要拿着房型ID和酒店ID判断房型是否存在,因为有可能是房型后来又新增的产品进来
            String RoomID = jsonObject.getString("RoomID");

            Map getHouseMap = new HashMap();
            getHouseMap.put("hotelId", hotelId);
            getHouseMap.put("eHouseId", RoomID);
            Map houseObjByObj = houseMapper.getHouseObjByObj(getHouseMap);
            if (houseObjByObj != null) {
                houseId = Integer.parseInt(houseObjByObj.get("houseId").toString());
            } else {
                houseId = houseMapper.getId();
                if (houseId == null) {
                    houseId = 10000000;
                }
                // step1:添加房型
                Map map1 = new HashMap();
                map1.put("houseId", houseId);
                map1.put("hotelId", hotelId);
                map1.put("houseName", jsonObject.getString("RoomName"));
                map1.put("eHouseName", jsonObject.getString("RoomName"));
                map1.put("eHouseId", jsonObject.getString("RoomID"));
                map1.put("bedType", jsonObject.getString("BedType"));
                map1.put("area", jsonObject.getString("Area"));
                map1.put("roomNum", jsonObject.getString("RoomNum"));
                map1.put("maxNum", jsonObject.getString("MaxNum"));
                houseMapper.insertHouse(map1);
            }

            // step2:添加产品
            JSONArray jsonArray1 = jsonObject.getJSONArray("RPList");
            for (int j = 0; j < jsonArray1.size(); j++) {
                String rpName = jsonArray1.getString(j);
                Map map2 = new HashMap();
                map2.put("rpName", rpName);
                map2.put("houseId", houseId);
                map2.put("isOnline", 0);
                addSum += rpMapper.insertRP(map2);
            }
        }
        if (addSum > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public List<Map> getHouseList(String hotelId, List<String> columnDateRange) {
        List<Map> mapList = new ArrayList<>();
        for (String nextNDay : columnDateRange) {
            Map map = new HashMap();
            map.put("filedAsName", nextNDay.replace("-", "_"));
            map.put("day", nextNDay);
            mapList.add(map);
        }
        List<Map> rpDataDate = houseMapper.getHouseList(hotelId, mapList);
        for (Map map : rpDataDate) {
            map.put("RQRange", new JSONArray());
        }
        return rpDataDate;
    }

    @Override
    @Transactional
    public int postUpdateHouseDimension(JSONObject jsonObject) {
        JSONArray rqRange = jsonObject.getJSONArray("rqRange");
        String startTime = rqRange.getString(0);
        String endTime = rqRange.getString(1);
        String houseId = jsonObject.getString("houseId");
        String yQuantityNum = jsonObject.getString("yQuantityNum");
        String nQuantityNum = jsonObject.getString("nQuantityNum");
        String roomStatus = jsonObject.getString("roomStatus");
        String hotelId1 = jsonObject.getString("hotelId");
        Long userId = SecurityUtils.getUserId();
        List<String> roomTypeCode = new ArrayList<>();
        roomTypeCode.add(houseId);

        if (nQuantityNum != null && !"".equals(nQuantityNum)) {
            // 需要改非保留房,非保留房不需要调用接口
            Map map = new HashMap();
            map.put("houseId", houseId);
            map.put("nQuantityNum", nQuantityNum);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            houseMapper.updateHouseDayData(map);
        }

        if (yQuantityNum != null && !"".equals(yQuantityNum)) {
            // 需要改保留房,房量接口需要调用,有保留房,必须是开房
            Map houseObj = houseMapper.getHouseObjByHouseId(houseId);
            String hotelId = houseObj.get("hotelId").toString();
            JSONObject jsonObject1 = groundService.updateRoomTypeAmount(hotelId, Integer.parseInt(yQuantityNum), startTime, endTime, 1, roomTypeCode, "OPEN");
            if (jsonObject1.getInteger("retcode") == 0) {
                Map map = new HashMap();
                map.put("houseId", houseId);
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                map.put("yQuantityNum", yQuantityNum);
                houseMapper.updateHouseDayData(map);
            }
        }

        if (!"1".equals(roomStatus)) {
            // 需要改房态,房态接口需要调用
            Map houseObj = houseMapper.getHouseObjByHouseId(houseId);
            String hotelId = houseObj.get("hotelId").toString();
            String status = "";
            if ("2".equals(roomStatus)) {
                status = "OPEN";
            }
            if ("3".equals(roomStatus)) {
                status = "CLOSE";
                // 保留房全设置为0
                JSONObject jsonObject1 = groundService.updateRoomTypeAmount(hotelId, 0, startTime, endTime, 1, roomTypeCode, "CLOSE");
                if (jsonObject1.getInteger("retcode") == 0) {
                    Map map = new HashMap();
                    map.put("houseId", houseId);
                    map.put("startTime", startTime);
                    map.put("endTime", endTime);
                    map.put("yQuantityNum", 0);
                    houseMapper.updateHouseDayData(map);
                }
            }
            JSONObject jsonObject1 = groundService.updateRoomTypeStatus(hotelId, startTime, endTime, 0, roomTypeCode, status);
            if (jsonObject1.getInteger("retcode") == 0) {
                Map map = new HashMap();
                map.put("houseId", houseId);
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                if ("OPEN".equals(status)) {
                    map.put("houseStatus", "1");
                } else {
                    map.put("houseStatus", "0");
                }
                houseMapper.updateHouseDayData(map);
            }
            logService.insertHouseRpPriceLog(hotelId, houseId, null, userId, "修改房态,将" + startTime + "至" + endTime + "的房态改为【" + status + "】");
        }
        return 1;
    }

    @Override
    public AjaxResult postBatchSwitchRoom(JSONObject jsonObject) {
        // 日期范围
        JSONArray rqRange = jsonObject.getJSONArray("rqRange");
        String startTime = rqRange.getString(0);
        String endTime = rqRange.getString(1);
        // 开关
        boolean switchRoom = jsonObject.getBoolean("switchRoom");
        String status;
        if (switchRoom) {
            status = "OPEN";
        } else {
            status = "CLOSE";
        }
        // 酒店ID
        String hotelId = jsonObject.getString("hotelId");

        // 房态为房型纬度,所以要找出该酒店所有的房型
        Map getHouseListMap = new HashMap();
        getHouseListMap.put("hotelId", hotelId);
        List<Map> houseListByHotelId = houseMapper.getHouseListByHotelId(getHouseListMap);
        List<String> roomTypeCode = new ArrayList<>();
        for (Map map : houseListByHotelId) {
            roomTypeCode.add(map.get("houseId").toString());
        }
        // 调用接口修改房态
        JSONObject jsonObject1 = groundService.updateRoomTypeStatus(hotelId, startTime, endTime, 0, roomTypeCode, status);
        if (jsonObject1.getInteger("retcode") == 0) {
            // 房态关成功了,如果是关房,同时关闭保留房
            if (switchRoom == false) {
                groundService.updateRoomTypeAmount(hotelId, 0, startTime, endTime, 1, roomTypeCode, "CLOSE");
            }
            for (String houseId : roomTypeCode) {
                // 改房态
                Map map = new HashMap();
                map.put("houseId", houseId);
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                if ("OPEN".equals(status)) {
                    map.put("houseStatus", "1");
                } else {
                    map.put("houseStatus", "0");
                }
                houseMapper.updateHouseDayData(map);
                logService.insertHouseRpPriceLog(hotelId, houseId, null, SecurityUtils.getUserId(), "修改房态,将" + startTime + "至" + endTime + "的房态改为【" + status + "】");

                // 改房量
                if (switchRoom == false) {
                    Map map1 = new HashMap();
                    map1.put("houseId", houseId);
                    map1.put("startTime", startTime);
                    map1.put("endTime", endTime);
                    map1.put("yQuantityNum", 0);
                    houseMapper.updateHouseDayData(map1);
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult postShelvesHouse(JSONObject jsonObject) {
        String hotelId = jsonObject.getString("hotelId");
        String houseId = jsonObject.getString("houseId");
        // step1:查看是否有在线的产品
        Map map = new HashMap();
        map.put("houseId", houseId);
        map.put("isOnline", 1);
        List<Map> onlineRpList = rpMapper.getRPByHouseId(map);
        if (onlineRpList.size() > 0) {
            return AjaxResult.error("下线失败,该房型有在线产品!");
        } else {
            // step2:关闭该房型所有房态
            List<Map> houseDayList = houseMapper.getHouseDayList(map);
            if (houseDayList.size() > 0) {
                String minDate = houseDayList.get(0).get("houseDay").toString();
                String maxDate = houseDayList.get(houseDayList.size() - 1).get("houseDay").toString();
                List<String> roomTypeCode = new ArrayList<>();
                roomTypeCode.add(houseId);
                JSONObject res1 = groundService.updateRoomTypeStatus(hotelId, minDate, maxDate, 0, roomTypeCode, "CLOSE");
                if (res1.getInteger("retcode") == 0) {
                    // step3:设置房态关房后删除该房型的时间维度数据
                    rpMapper.deleteRpDataByHouseId(houseId);
                    houseMapper.deleteHouseDataByHouseId(houseId);
                }
            }
            // step4:艺龙下线
            JSONObject res1 = groundService.offlineMapping("RoomType", hotelId, houseId, "");
            int i = 0;
            if (res1.getInteger("retcode") == 0) {
                // step5:最后设置本地产品上线状态为0
                Map map1 = new HashMap();
                map1.put("houseId", houseId);
                map1.put("isOnline", 0);
                i = houseMapper.updateHouseByMap(map1);
            }
            if (i > 0) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("下线失败,请联系管理员");
            }
        }
    }

    @Override
    public AjaxResult postUpdateRoomName(JSONObject jsonObject) {
        String hotelId = jsonObject.getString("hotelId");
        Map hotelObj = hotelMapper.getHotelObjByHotelId(hotelId);
        String eHotelId = hotelObj.get("eHotelId").toString();
        String hotelInfo = ElongUtils.getHotelInfo(eHotelId);
        JSONObject jsonObject1 = JSONObject.parseObject(hotelInfo);
        JSONArray jsonArray = jsonObject1.getJSONObject("Result").getJSONArray("Rooms");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
            String RoomID = jsonObject2.getString("RoomID");
            String RoomName = jsonObject2.getString("RoomName");

            Map map = new HashMap();
            map.put("eHouseId", RoomID);
            map.put("hotelId", hotelId);
            map.put("houseName", RoomName);
            map.put("eHouseName", RoomName);
            houseMapper.updateHouseByMap(map);
        }
        return AjaxResult.success();
    }
}